﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace XXF.BaseService.ServiceCenter.Service.SystemRuntime
{
    /// <summary>
    /// 类型转换(未来是用Emit方式,用于提升性能)
    /// </summary>
    public class TypeConvertHelper
    {
        /// <summary>
        /// 简单类型转换
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="o"></param>
        /// <returns></returns>
        public static T Convert<T>(object o)
        {
            if (o == null)
                return default(T);
            var type = o.GetType();
            if (o.GetType() == typeof(T))
                return (T)o;
            //return (T)System.Convert.ChangeType(o, typeof(T));
            /*此处只有双方类型不一致时,采用*/
            return JsonConvert.DeserializeObject<T>( JsonConvert.SerializeObject(o));
        }

        public static object Convert(Type totype,object o)
        {
            if (o == null)
                return o;
            var type = o.GetType();
            if (o.GetType() == totype)
                return o;
            //return (T)System.Convert.ChangeType(o, typeof(T));
            return JsonConvert.DeserializeObject( JsonConvert.SerializeObject(o),totype);
        }
    }
}
